<template>
	<div class="space-y-4 flex flex-col items-center">
		<span class="flex justify-center font-bold text-3xl pb-6 items-center"> SleepLess </span>
		<label class="input input-bordered flex items-center gap-2 w-2/3">
			账号
			<a-input
				v-model:value="loginInfo.username"
				type="text"
				class="grow"
				placeholder="username"
				name="username"
				autocomplete="username"
			></a-input>
		</label>
		<label class="input input-bordered flex items-center gap-2 w-2/3">
			密码
			<a-input-password
				v-model:value="loginInfo.password"
				placeholder="password"
				name="password"
				autocomplete="current-password"
			/>
		</label>
		<div class="form-control w-1/2">
			<label class="label cursor-pointer flex-row flex">
				<span class="label-text text-base font-bold">3 天内免登录</span>
				<input v-model="loginInfo.save" type="checkbox" class="checkbox w-4" />
			</label>
		</div>
		<div class="flex space-x-4 justify-center flex-col">
			<a-button class="text-lg text-center" @click="login">登录</a-button>
			<a>忘记密码</a>
		</div>
	</div>
</template>

<script lang="ts" setup>
	import { reactive } from 'vue'
	import { type LoginType } from '@/types/user'
	import '@/utils/axios/request'
	import { push } from 'notivue'
	import { useUserStore } from '@/store/user'
	import { _getUserInfo, _login } from '@/api/user'

	const userStore = useUserStore()

	const loginInfo = reactive<LoginType>({
		username: '',
		password: '',
		save: false,
	})

	function init() {
		loginInfo.password = ''
		loginInfo.password = ''
		loginInfo.save = false
	}
	function login() {
		userStore.init()
		if (loginInfo.username == '' || loginInfo.password == '') {
			push.error({
				title: '数据错误',
				message: '未填写完整信息',
			})
			return
		}

		let params = {
			username: loginInfo.username,
			password: loginInfo.password,
		}

		_login(params).then((data: any) => {
			userStore.setToken(data.token)
			if (loginInfo.save) {
				userStore.setLoginStatus(String(loginInfo.save))
			}
			init() //把原本的账号密码清空
			emit('loginCancel') // 触发事件
			_getUserInfo(null).then((data: any) => {
				userStore.login(data)
			})
		})
	}

	const emit = defineEmits(['loginCancel'])
</script>
